﻿using System;

class FindMaxSquareSum

            // Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3 that has maximal sum of its elements.

{
    static void Main()
    {
        Console.Write("Enter number of rows 'N', such that N>3: ");
        int rowsN = int.Parse(Console.ReadLine());
        Console.Write("Enter number of rows 'M', such that M>3: ");
        int colsM = int.Parse(Console.ReadLine());
        int[,] matrix = new int[rowsN, colsM];
        Console.WriteLine();
        
        for (int row = 0; row < rowsN; row++)
        {
            for (int col = 0; col < colsM; col++)
            {
                Console.Write("Element on position [{0},{1}] = ", row, col);
                matrix[row, col] = int.Parse(Console.ReadLine());
            }
        }

        int maxSum = 0;
        int sum = 0;
        int rowIndex = 0;
        int colIndex = 0;

        for (int row = 0; row < rowsN - 2; row++)
        {
            for (int col = 0; col < colsM - 2; col++)
            {
                for (int i = row; i <= row + 2; i++)
                {
                    for (int j = col; j <= col + 2; j++)
                    {
                        sum += matrix[i, j];
                    }
                }
                if (sum > maxSum)
                {
                    maxSum = sum;
                    rowIndex = row;
                    colIndex = col;
                }
                sum = 0;
            }
        }
        Console.WriteLine();
        Console.WriteLine("The max sum of a 3x3 square inside the matrix is: {0} and this square is: \n", maxSum);
        for (int row = rowIndex; row <= rowIndex + 2; row++)
        {
            for (int col = colIndex; col <= colIndex + 2; col++)
            {
                Console.Write("{0,4}", matrix[row, col]);
            }
            Console.WriteLine();
        }
    }
}

